<template>
  <el-sub-menu v-if="menuData.children.length>0" :index="menuData.id">
    <template #title>
      <el-icon>
        <component :is="menuData.icon" />
      </el-icon>
      <span>{{ menuData.name }}</span>
    </template>
    <menu-item v-for="menu in menuData.children" :menuData="menu" :key="menu.id"></menu-item>
  </el-sub-menu>
  <el-menu-item v-else :index="menuData.id" @click.self="handleMenuClick(menuData.action, menuData.target)">
    <el-icon>
      <component :is="menuData.icon" />
    </el-icon>
    {{ menuData.name }}
  </el-menu-item>
  <star-dialog :dialogUrl="dialogUrl" :dialogVisible="dialogVisible"></star-dialog>
</template>

<script setup>
import router from '@/router'
import { ref, defineProps } from 'vue'
import { ElMessage } from 'element-plus'
import { clearCache } from '@/api/system/menu/MenuClick'
import starDialog from '@/components/common/dialog/StarDialog'

const dialogUrl = ref('')
const dialogVisible = ref(false)
const props = defineProps({
  menuData: Object
})

const handleMenuClick = (route, target) => {
  if (target === 'divmain') {
    openDialog(route)
    return
  }
  if (route.indexOf('javascript') > -1) {
    const methodName = route.substr(11)

    if (typeof methods[methodName] === 'function') {
      methods[methodName]()
    }
  } else {
    router.push(route)
  }
}

const openDialog = (route) => {
  dialogUrl.value = route
  dialogVisible.value = true
}

const clear = () => {
  clearCache().then(() => {
    ElMessage({
      message: '清除成功！',
      type: 'success',
      duration: 500
    })
  }).catch((error) => {
    ElMessage.error(error.message || '清除失败！')
  })
}

const methods = {
  clear
}

</script>
